<template>
  <ContentWrap :bodyStyle="{ paddingTop: '5px' }">
    <Back :backOption="backOption" />
    <div class="h-full">
      <el-form label-width="100px" :model="queryForm" ref="queryFormRef" inline class="flex">
        <el-form-item label="文件名称" prop="name" class="flex-1"
          ><el-input style="width: 50%" v-model="queryForm.name" placeholder="请输入文件名称"
        /></el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form
        label-width="100px"
        label-position="left"
        :model="formData"
        ref="editClusteringRef"
        :rules="rules"
      >
        <el-row class="mb-10px" :gutter="100">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="name">
              <ns-input
                style="max-width: 600px"
                v-model="formData.name"
                :disabled="true"
                placeholder="请输入任务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结果名称" prop="result">
              <el-input
                style="max-width: 600px"
                v-model="formData.result"
                placeholder="请输入结果名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="100" class="mb-50px">
          <el-col :span="step === 1 ? 24 : 12">
            <el-form-item label="对比阈值" prop="percentage" class="mb-20px">
              <el-row style="width: 100%" :gutter="20">
                <el-col :span="22">
                  <el-slider v-model="formData.percentage" @change="sliderChange" />
                </el-col>
                <el-col :span="2">
                  <span class="percent-icon">{{ formData.percentage }}%</span>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="聚类结果">
              <div
                class="w-full b-1 b-gray-3 border-rd-3 border-style-dashed p-5 pl-3 pr-3"
                v-show="step === 1"
              >
                <el-tree
                  :data="tableData"
                  v-loading="treeLoading"
                  :props="defaultProps"
                  default-expand-all
                  highlight-current
                  node-key="nodeId"
                  :show-checkbox="false"
                >
                  <template #default="{ node, data }">
                    <div class="custom-tree-node">
                      <el-link
                        style="font-size: 16px"
                        v-if="node.isLeaf"
                        @click="downloadFile(data.manageId, node.label)"
                        type="primary"
                      >
                        {{ node.label }}</el-link
                      >

                      <span v-else> {{ node.label }}</span>
                    </div>
                  </template></el-tree
                >
              </div>
              <div
                class="w-full b-1 b-gray-3 border-rd-3 border-style-dashed p-5 pl-3 pr-3"
                v-show="step === 2"
              >
                <div class="s-btn-list">
                  <el-button @click="allSelectSwitch">全选 / 全不选</el-button>
                  <el-button :icon="Top" type="primary" @click="handleExport">导出结果</el-button>
                </div>
                <el-tree
                  :data="tableData"
                  ref="treeRef"
                  :props="defaultProps"
                  default-expand-all
                  highlight-current
                  node-key="nodeId"
                  :default-checked-keys="clusterData.nodeIds"
                  :show-checkbox="true"
                  :expand-on-click-node="false"
                  :allow-drop="allowDrop"
                  draggable
                >
                  <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <div v-if="!node.isEdit" class="w-full">
                        <div
                          v-if="node.isLeaf && !data.nodeId.startsWith('pid_')"
                          class="file-h-wrap"
                        >
                          <el-link
                            style="font-size: 16px"
                            @click="downloadFile(data.manageId, node.label)"
                            type="primary"
                          >
                            {{ node.label }}</el-link
                          >
                        </div>
                        <span v-else>{{ node.label }}</span>
                      </div>

                      <ns-input
                        v-model="data.name"
                        style="width: 200px"
                        placeholder="请输入"
                        v-else
                      />
                      <template v-if="node.isLeaf">
                        <template v-if="!node.isEdit">
                          <el-icon size="22" color="#409eff" @click.stop="chooseFile(node)">
                            <Aim />
                          </el-icon>
                          <el-icon
                            size="22"
                            color="#409eff"
                            @click="editCategory(node, data, 'edit')"
                          >
                            <Edit />
                          </el-icon>
                          <el-icon
                            size="22"
                            color="#f56c6c"
                            @click="editCategory(node, data, 'delete')"
                          >
                            <Delete />
                          </el-icon>
                        </template>
                        <template v-else>
                          <el-icon
                            class="mt-5px"
                            size="22"
                            color="#409eff"
                            @click="editCategory(node, data, 'check')"
                          >
                            <Check />
                          </el-icon>
                        </template>
                      </template>
                      <div v-if="data.nodeId.startsWith('pid_')" class="node-icon-list">
                        <template v-if="!node.isEdit">
                          <el-icon
                            size="22"
                            color="#409eff"
                            @click="editCategory(node, data, 'edit')"
                          >
                            <Edit />
                          </el-icon>
                        </template>
                        <template v-else>
                          <el-icon
                            size="22"
                            color="#409eff"
                            @click="editCategory(node, data, 'plus')"
                          >
                            <Plus />
                          </el-icon>
                          <el-icon
                            size="22"
                            color="#409eff"
                            @click="editCategory(node, data, 'check')"
                          >
                            <Check />
                          </el-icon>
                          <el-icon
                            size="22"
                            color="#f56c6c"
                            @click="editCategory(node, data, 'delete')"
                          >
                            <Delete />
                          </el-icon>
                        </template>
                      </div>
                    </span>
                  </template>
                </el-tree>
              </div>
            </el-form-item>
            <div style="text-align: center">
              <el-button
                type="primary"
                @click="submit('下发文件', 'left')"
                v-show="step === 2"
                :disabled="treeLoading || formLoading"
                >下发文件</el-button
              >
              <el-button
                type="primary"
                @click="submit('添加至文件管理', 'left')"
                v-show="step === 2"
                :disabled="treeLoading || formLoading"
                >添加至文件管理</el-button
              >
            </div>
          </el-col>
          <el-col :span="12" v-if="step === 2">
            <template v-if="!!selectedFile">
              <el-form-item label="文件对比" prop="percentage" class="!mb-20px">
                <div class="file-info">
                  <el-icon class="mr-5px" :size="22"><Document /></el-icon>{{ selectedFile.name }}
                </div>
              </el-form-item>
              <el-form-item label="对比阈值" prop="percentage" class="mb-20px">
                <el-row style="width: 100%" :gutter="20">
                  <el-col :span="22">
                    <el-slider
                      :disabled="treeLoading"
                      v-model="selectedFileData.percentage"
                      @change="fileSliderChange"
                    />
                  </el-col>
                  <el-col :span="2">
                    <span class="percent-icon">{{ selectedFileData.percentage }}%</span>
                  </el-col>
                </el-row>
              </el-form-item>
              <div
                class="mb-18px w-full b-1 b-gray-3 border-rd-3 border-style-dashed p-5 pl-3 pr-3"
                v-show="step === 2"
              >
                <div class="s-btn-list">
                  <el-button @click="allSelectSwitchLeft">全选 / 全不选</el-button>
                </div>
                <el-tree
                  :data="selectedFileData.resultList"
                  ref="treeFileResultRef"
                  :props="defaultProps"
                  default-expand-all
                  highlight-current
                  node-key="nodeId"
                  :show-checkbox="true"
                  :expand-on-click-node="false"
                >
                  <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <el-link
                        style="font-size: 16px"
                        v-if="node.isLeaf"
                        @click="downloadFile(data.manageId, node.label)"
                        target="_blank"
                        type="primary"
                      >
                        {{ node.label }}</el-link
                      >
                      <span v-else>{{ node.label }}</span>
                    </span>
                  </template>
                </el-tree>
              </div>
              <div style="text-align: center">
                <el-button
                  type="primary"
                  @click="submit('下发文件', 'right')"
                  v-show="step === 2"
                  :disabled="treeLoading || formLoading"
                  >下发文件</el-button
                >
                <el-button
                  type="primary"
                  @click="submit('添加至文件管理', 'right')"
                  v-show="step === 2"
                  :disabled="treeLoading || formLoading"
                  >添加至文件管理</el-button
                >
              </div>
            </template>
            <div v-else class="tips-info w-full b-1 b-gray-3 border-rd-3 border-style-dashed p-5"
              ><span> 可在左侧选择基准文件进行对比 </span>
            </div>
          </el-col>
        </el-row>

        <div style="text-align: center">
          <el-button type="primary" @click="submit()" :disabled="treeLoading || formLoading"
            >保存</el-button
          >
          <el-button @click="handleClose">取消</el-button>
        </div>
      </el-form>
    </div>
  </ContentWrap>
  <DistributeFiles ref="distributeFilesRef" @success="toAsset" />
  <AddFilesManage ref="addFilesManageRef" @success="toManage" />
</template>

<script setup lang="ts">
import Back from '@/components/Back/index.vue'
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import download from '@/utils/download'
import {
  getClusterTask,
  createClusterResult,
  fileToAsset,
  fileToManage,
  updateClusterResult,
  getClusterTaskResultInfo,
  exportClusterResult,
  deleteClusterResultFile,
  editClusterResultFile
} from '@/api/develop/clusterTask'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { v4 as uuidv4 } from 'uuid'
import type { AllowDropType } from 'element-plus/es/components/tree/src/tree.type'
import { Edit, Check, Plus, Delete, Top, Document, Aim, Close } from '@element-plus/icons-vue'
import Nzh from 'nzh/cn'
import DistributeFiles from './dialog/DistributeFiles.vue'
import AddFilesManage from './dialog/AddFilesManage.vue'
import { ElMessageBox, ElStep, ElTree } from 'element-plus'
import { useFilePreview } from '../file/useFilePreview'
import dayjs from 'dayjs'
type ClusterResults = {
  clusterDocNum: number[]
  clusterIDs: number[]
  clusterInnerSimilarity: number[]
  threshold: number
}
type TreeItem = {
  name: string
  [key: string]: any
  children?: TreeItem[]
}
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { downloadFile } = useFilePreview()

const router = useRouter()
const { params } = useRoute()

const backOption = computed(() => {
  return {
    title: step.value === 2 ? '聚类结果' : '编辑结果'
  }
})

const treeLoading = ref(false) // 树形数据的加载中
const formLoading = ref(false)
const queryFormRef = ref()

const distributeFilesRef = ref<InstanceType<typeof DistributeFiles>>()
const addFilesManageRef = ref<InstanceType<typeof AddFilesManage>>()
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeFileResultRef = ref<InstanceType<typeof ElTree>>()

const queryForm = ref({ name: '' })

const data = reactive({
  formData: {
    result: '',
    name: '',
    percentage: 0
  },
  rules: {
    result: [{ required: true, message: '请输入结果名称', rigger: ['blur', 'change'] }],
    name: [{ required: true, message: '请输入任务名称', rigger: ['blur', 'change'] }]
  },
  step: 1 as 1 | 2
})

const { formData, rules, step } = toRefs(data)

const defaultProps = {
  children: 'children',
  label: 'name'
}

const tableData = ref<TreeItem[]>([])

const clusterData = reactive({
  clusterResults: [] as ClusterResults[],
  fileInfoList: [],
  nodeIds: [] as string[]
})

function sliderChange(val) {
  const curClusterData = clusterData.clusterResults.find((item) => {
    return item.threshold === val / 100
  })
  if (curClusterData) setTreeData(curClusterData)
}

function setTreeData({ clusterDocNum, clusterIDs }) {
  const fileList_ = toRaw(clusterData.fileInfoList) as any[]

  const treeData_: TreeItem[] = []
  const nodeIds_: string[] = []

  // 设定几个分类
  clusterDocNum.forEach((_, index) => {
    const nodeId = `pid_${index}`
    treeData_.push({
      name: '类别' + Nzh.encodeS(index + 1),
      nodeId: nodeId,
      children: []
    })
    nodeIds_.push(nodeId)
  })

  // 把文件放到对应分类下面
  if (fileList_ && fileList_.length === clusterIDs.length) {
    clusterIDs.forEach((item, index) => {
      treeData_[item - 1]!.children?.push({
        nodeId: fileList_[index].id,
        name: fileList_[index].name,
        manageId: fileList_[index].id,
        path: fileList_[index].path
      })
      nodeIds_.push(fileList_[index].id)
    })
  }

  tableData.value = treeData_
  clusterData.nodeIds = nodeIds_
}

const allowDrop = (draggingNode: Node, dropNode: Node, type: AllowDropType) => {
  return (
    draggingNode.isLeaf &&
    dropNode.data.nodeId.startsWith('pid_') &&
    !draggingNode.data.nodeId.startsWith('pid_') &&
    type === 'inner'
  )
}

const editIds = [] as string[] // 设置过的nodeid
const filterTable = (table, id) => {
  for (let i = 0; i < table.length; i++) {
    // 使用索引进行循环
    const item = table[i]

    if (item.children && item.children.length > 0) {
      const foundInChildren = filterTable(item.children, id) // 检查子节点
      if (foundInChildren) return true // 如果在子节点中找到了，提前返回
    } else if (item.nodeId === id) {
      table.splice(i, 1) // 删除匹配项
      return true // 返回true表示找到了并已删除
    }
  }

  return false // 如果未找到匹配项，则返回false
}
async function editCategory(node, data, type: 'edit' | 'delete' | 'check' | 'plus') {
  if (type === 'edit') {
    node.isEdit = true
    if (!editIds.includes(data.nodeId)) editIds.push(data.nodeId)
  }
  if (type === 'check') {
    node.isEdit = false
  }
  if (type === 'plus') {
    const uuid_ = uuidv4()
    const index_ = tableData.value.findIndex((item) => item.nodeId === data.nodeId)
    tableData.value.splice(index_ + 1, 0, {
      name: '新建类型',
      nodeId: `pid_${uuid_}`,
      children: []
    })
  }
  if (type === 'delete') {
    try {
      const isLeaf = node.isLeaf && !data.nodeId.startsWith('pid_')
      // 删除的二次确认
      const messageText = isLeaf ? '确认删除此文件？' : '确认删除该分类以及分类下所有文件？'
      await message.delConfirm(messageText)
      if (isLeaf) {
        filterTable(tableData.value, data.nodeId)
        return
      }
      const index_ = tableData.value.findIndex((item) => item.nodeId === data.nodeId)
      if (tableData.value.length > 1) {
        tableData.value.splice(index_, 1)
      } else {
        message.alertWarning('至少存在一个分类')
      }
    } catch {}
  }
}

// 获取聚类任务详情
async function getTaskDetail() {
  treeLoading.value = true
  try {
    const res = await getClusterTask(params.taskId as string)
    data.formData.name = res.name
    data.formData.result = `${res.name} ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`
    clusterData.clusterResults = res.clusterResults || []
    clusterData.fileInfoList = res.fileManageInfoList
    sliderChange(formData.value.percentage)
  } finally {
    treeLoading.value = false
  }
}

// 获取聚类结果详情
async function getResultDetail() {
  treeLoading.value = true
  try {
    const res = await getClusterTaskResultInfo(params.resultId as string, queryForm.value.name)
    const num_ = (params?.threshold && Number(params?.threshold) * 100) || 0
    data.formData.percentage = parseInt(num_.toFixed(0))
    data.formData.result = res.name
    const nodeIds_: string[] = []
    tableData.value = res.filesInfo?.map((cate) => {
      const child_ = cate.children.map((child) => {
        nodeIds_.push(child.id)
        return {
          nodeId: child.id,
          name: child.name,
          manageId: child.manageId,
          path: child.path
        }
      })
      const uuid_ = uuidv4()
      nodeIds_.push(`pid_${uuid_}`)
      return {
        name: cate.name,
        nodeId: `pid_${uuid_}`,
        children: child_
      }
    })

    clusterData.nodeIds = nodeIds_
  } finally {
    treeLoading.value = false
  }
}

// 获取任务名称
async function setTaskName() {
  treeLoading.value = true
  try {
    const res = await getClusterTask(params.taskId as string)
    data.formData.name = res.name
    clusterData.clusterResults = res.clusterResults || []
    clusterData.fileInfoList = res.fileManageInfoList
  } finally {
    treeLoading.value = false
  }
}

const editClusteringRef = ref<FormInstance>()

let resultId

const curResultId = computed(() => resultId || params.resultId)

let curFormPosition: 'left' | 'right' | undefined
async function submit(type?: '添加至文件管理' | '下发文件', position?: 'left' | 'right') {
  // 校验表单
  await editClusteringRef.value?.validate()
  if (step.value === 1) {
    try {
      resultId = await createClusterResult({
        name: formData.value.result,
        taskId: params.taskId,
        threshold: formData.value.percentage / 100,
        fileInfo: toRaw(tableData.value)
      })

      message.success(t('common.createSuccess'))
    } finally {
      formLoading.value = false
    }

    // 下一步
    step.value = 2
    return
  }
  curFormPosition = position

  let fileResultChecked

  if (step.value === 2) {
    if (type === '下发文件') {
      if (isFileEmpty(treeRef.value!) && curFormPosition === 'left') {
        message.alertWarning('请至少选择一个文件')
        return
      }

      // if (fileResultChecked.length == 0 && curFormPosition === 'right') {
      //   message.alertWarning('请至少选择一个文件')
      //   return
      // }

      distributeFilesRef.value?.open()
      return
    }
    if (type === '添加至文件管理') {
      if (position === 'right') {
        fileResultChecked =
          (treeFileResultRef.value && treeFileResultRef.value!.getCheckedNodes()) || []
        if (fileResultChecked.length == 0) {
          message.alertWarning('请至少选择一个文件')
          return
        }
        addFilesManageRef.value?.open()
      } else {
        fileResultChecked = (treeRef.value && treeRef.value!.getCheckedNodes()) || []
        console.log('fileResultChecked', fileResultChecked)
        if (fileResultChecked.length == 0) {
          message.alertWarning('请至少选择一个文件')
          return
        }
        addFilesManageRef.value?.open()
      }

      return
    }
    if (curResultId.value) {
      // const treeData_ = getCheckTreeData()
      const treeData_ = cloneDeep(toRaw(tableData.value))
      if (treeData_.length == 0) {
        message.alertWarning('请至少选择一个文件')
        return
      }
      setSaved()
      await editResult(treeData_)
      message.success(t('common.updateSuccess'))
    }
  }
}

// 保存结果
async function editResult(fileInfo) {
  formLoading.value = true
  try {
    await updateClusterResult({
      id: curResultId.value,
      name: formData.value.result,
      taskId: params.taskId,
      threshold: formData.value.percentage / 100,
      fileInfo: fileInfo
    })
  } finally {
    formLoading.value = false
  }
}

//下发文件回调
async function toAsset(data) {
  const treeData_ = getCheckTreeData()
  const fileResultChecked =
    (treeFileResultRef.value && treeFileResultRef.value!.getCheckedNodes()) || []

  distributeFilesRef.value?.setBtnStatus(true)
  formLoading.value = true
  try {
    // if (treeData_.length > 0) {
    //   await editResult(treeData_) // 先保存
    // }
    const list_ = curFormPosition === 'left' ? treeData_ : fileResultChecked
    const res = await fileToAsset({
      ...data,
      fileInfo: list_
    })
    if (res.sameList && res.sameList.length > 0) {
      const nameList = res.sameList.map((item) => item.name).join('、')
      message.warning(`${nameList} 文件已存在`)
    } else {
      message.success(t('common.createSuccess'))
    }
    distributeFilesRef.value?.close()
  } finally {
    distributeFilesRef.value?.setBtnStatus(false)
    formLoading.value = false
  }
}

//添加至文件管理
async function toManage(data?: any) {
  const treeData_ = getCheckTreeData()
  let fileResultChecked
  if (isFileEmpty(treeRef.value!) && curFormPosition === 'left') {
    message.alertWarning('请至少选择一个文件')
    return
  }

  if (curFormPosition === 'left') {
    fileResultChecked = treeData_
    // (treeRef.value && treeRef.value!.getCheckedNodes().filter((item) => item.manageId)) || []
    console.log('fileResultChecked', fileResultChecked)
  } else {
    fileResultChecked =
      (treeFileResultRef.value && treeFileResultRef.value!.getCheckedNodes()) || []
  }

  formLoading.value = true
  if (data && fileResultChecked.length > 0) {
    addFilesManageRef.value?.setBtnStatus(true)
    //右侧选择
    try {
      await fileToManage({
        fileInfo: fileResultChecked,
        ...data
      })
      message.success(t('common.createSuccess'))
      addFilesManageRef.value?.close()
    } finally {
      addFilesManageRef.value?.setBtnStatus(false)
      formLoading.value = false
    }
    return
  }

  //左侧选择
  // try {
  //   // await editResult(treeData_) // 先保存
  //   await fileToManage({
  //     fileInfo: treeData_,
  //     pid: '0'
  //   })
  //   message.success(t('common.createSuccess'))
  // } finally {
  //   formLoading.value = false
  // }
}

// 定义递归过滤方法
function deepFilterTree(list, checkedKeys) {
  return list.filter((item) => {
    if (item.children && checkedKeys.includes(item.nodeId)) {
      item.children = deepFilterTree(item.children, checkedKeys)
    }

    // 判断当前节点是否符合过滤要求
    return checkedKeys.includes(item.nodeId)
  })
}

function getCheckTreeData() {
  const checkedKeys = treeRef.value!.getCheckedNodes(false, true)?.map((item) => item.nodeId)

  const curTreeList_ = cloneDeep(toRaw(tableData.value))

  return deepFilterTree(curTreeList_, checkedKeys)
}

let isAll = true

function allSelectSwitch() {
  if (!isAll) {
    treeRef.value!.setCheckedKeys(clusterData.nodeIds)
  } else {
    treeRef.value!.setCheckedKeys([])
  }
  isAll = !isAll
}

let isAllLeft = false

function allSelectSwitchLeft() {
  if (!isAllLeft) {
    treeFileResultRef.value && treeFileResultRef.value!.setCheckedKeys(selectedFileData.allNodeIds)
  } else {
    treeFileResultRef.value && treeFileResultRef.value!.setCheckedKeys([])
  }
  isAllLeft = !isAllLeft
}

// function setOtherClear(type: 1 | 2) {
//   if (type === 1) {
//     treeRef.value && treeRef.value!.setCheckedKeys([])
//   }
//   if (type === 2) {
//     treeFileResultRef.value && treeFileResultRef.value!.setCheckedKeys([])
//   }
// }

function handleClose() {
  router.push({ name: 'DevelopClustering' })
}

// 设置节点状态为保存状态
function setSaved() {
  for (const id of editIds) {
    const node = treeRef.value!.getNode(id) as any
    if (node.isEdit!) node.isEdit! = false
  }
}

const exportLoading = ref(true)
const handleExport = async () => {
  let data = null
  try {
    // 导出的二次确认
    // await message.exportConfirm()
    const treeData_ = getCheckTreeData()

    if (isFileEmpty(treeRef.value!)) {
      message.alertWarning('请至少选择一个文件')
      return
    }

    const ids: string[] = []
    for (const item of treeData_) {
      if (item.children) {
        for (const children of item.children) {
          ids.push(children.manageId)
        }
      }
    }

    // 发起导出
    exportLoading.value = true
    data = await exportClusterResult({
      ids: ids.join(',')
    })
    download.txt(data, '聚类结果.txt')
  } catch (error) {
    ElMessage.error(error)
  } finally {
    exportLoading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  getResultDetail()
}
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const selectedFileData = reactive({
  selectedFile: null as any,
  percentage: 0,
  fileIndex: -1,
  resultList: [] as TreeItem[],
  allNodeIds: [] as string[]
})
const fileSet = new Set<string>()
const { selectedFile } = toRefs(selectedFileData)

function fileSliderChange(val) {
  getFileList(val)
}

function chooseFile(node: any) {
  selectedFileData.selectedFile = node.data

  selectedFileData.fileIndex = clusterData.fileInfoList.findIndex(
    (file: any) => node.data.manageId === file.id
  )
  selectedFileData.percentage = 0
  getFileList(selectedFileData.percentage)
}

function getFileList(threshold: number) {
  fileSet.clear()
  selectedFileData.resultList = []
  selectedFileData.allNodeIds = []
  for (const item of clusterData.clusterResults) {
    const clusterIdIndex = item.clusterIDs[selectedFileData.fileIndex]
    const similarity = item.clusterInnerSimilarity[clusterIdIndex - 1]
    if (similarity >= threshold / 100) {
      item.clusterIDs.forEach((item, i) => {
        if (item === clusterIdIndex) {
          fileSet.add(JSON.stringify(clusterData.fileInfoList[i]))
        }
      })
    }
  }
  const fileArr = Array.from(fileSet).map((item) => JSON.parse(item))

  const list_ = fileArr.map((file) => {
    return {
      nodeId: file.id,
      name: file.name,
      manageId: file.id,
      path: file.path
    }
  })
  // 删除本身
  const index_ = list_.findIndex((file) => file.manageId === selectedFileData.selectedFile.manageId)
  list_.splice(index_, 1)
  selectedFileData.resultList = list_
  selectedFileData.allNodeIds = list_.map((file) => file.nodeId)
}

function isFileEmpty(treeRef: InstanceType<typeof ElTree>) {
  const files = treeRef
    .getCheckedNodes(true, false)
    .filter((item) => !item.nodeId.startsWith('pid_'))
  return files.length === 0
}

onMounted(() => {
  if (params.resultId) {
    //有结果id，进入步骤2，编辑结果
    step.value = 2
    setTaskName()
    getResultDetail()

    formData.value.percentage
  } else {
    //进入步骤1，新增结果
    step.value = 1
    getTaskDetail() // 获取任务详情
    const process = params.taskId.slice(-2)
    formData.value.percentage = Number(process || '34')
  }
})
</script>

<style lang="scss" scoped>
.h-full {
  padding: 20px;
}
.percent-icon {
  border: 1px solid #eee;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding: 2px 10px;
  width: 40px;
  text-align: center;
  display: inline-block;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  padding-right: 8px;
}

.node-icon-list {
  display: flex;
  align-items: center;
  gap: 0 10px;
}
.s-btn-list {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
}
.file-info {
  display: flex;
  align-items: center;
  font-size: 18px;
}
.tips-info {
  min-height: 150px;
  display: flex;
  color: #909399;
  align-items: center;
  justify-content: center;
}
.file-h-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
</style>
